package com.wing.productionPlan.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.Idempotent;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.entity.ProcessInfo;
import com.wing.enterprise.product.model.response.ProcessInfoVO;
import com.wing.enterprise.product.model.response.ProductProcessMaterialVO;
import com.wing.productionPlan.model.entity.AuditRecord;
import com.wing.productionPlan.model.entity.ProductionCategory;
import com.wing.productionPlan.model.entity.ProductionPlan;
import com.wing.productionPlan.model.entity.ProductionPlanRecord;
import com.wing.productionPlan.model.request.BatchProductionPlanAddForm;
import com.wing.productionPlan.model.request.ProductionPlanForm;
import com.wing.productionPlan.model.request.SubmitProductionPlanOutForm;
import com.wing.productionPlan.model.response.*;
import com.wing.productionPlan.service.*;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 在制品controller
 * @author hz
 */
@Slf4j
@Validated
@Api(value = "Admin-生产在制品管理", tags = "#/productionPlan/productionProgress")
@RestController("productionInProgressController")
@RequestMapping("productionPlan/admin/productionProgress")
@RequiredArgsConstructor
public class ProductionInProgressController {

    private final ProductionPlanRecordService productionPlanRecordService;

    @ApiOperation(value = "查询所有在制品", notes = "搜索-在制品")
    @GetMapping("/list")
    public PageResult<ProductionPlanRecordReportVO> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            ,  String skuName
            ,  String skuCode
            ,  String skuSpec
    ) {

        Page<ProductionPlanRecordReportVO> pg = new Page<>(page, limit);
        //默认查询排产的
        List<String> status = new ArrayList<>();
        status.add("1");
        status.add("2");
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("status", status);
        paramMap.put("skuName", skuName);
        paramMap.put("skuCode", skuCode);
        paramMap.put("skuSpec", skuSpec);
        //1. 在制品涉及到制造令信息
        IPage<ProductionPlanRecordReportVO> planRecordCountInfo = productionPlanRecordService.getPlanRecordCountByIn(pg,paramMap);

        //2. 查询其他信息
        List<ProductionPlanRecordReportVO> records = planRecordCountInfo.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            //查询物料信息
            List<Long> collect = records.stream()
                    .map(ProductionPlanRecordReportVO::getProductDetailId)
                    .filter(productDetailId -> ObjectUtil.isNotEmpty(productDetailId))
                    .collect(Collectors.toList());

            //查询产品库存
            List<ProductCountInWarhousesVo> productCountInWarhousesVo =
                    this.productionPlanRecordService.warehouseKc(collect);

            //查询不同物料下的计划生产数
            List<ProductionPlanProDetailVO> vos = productionPlanRecordService.getplanCountBySkuList(collect);
            //合格不合格
            List<ProductionPlanProDetailVO> vos2 = productionPlanRecordService.getWorkOrderCountBySkuList(collect);
            //入库数
            List<ProductionPlanProDetailVO> vos3 = productionPlanRecordService.getInWarehouseList(collect);

            //查询不同物料的
            //迭代
            for (ProductionPlanRecordReportVO record : records) {

                //设置库存
                for (ProductCountInWarhousesVo countInWarhousesVo : productCountInWarhousesVo) {
                    if (record.getProductDetailId().equals(countInWarhousesVo.getProductDetailId())) {
                        record.setInventoryQuantity(countInWarhousesVo.getHaveQuantity());
                    }
                }
                //设置计划生产数
                for (ProductionPlanProDetailVO vo : vos) {
                    if (vo.getProductDetailId().equals(record.getProductDetailId())) {
                        record.setProductionQuantity(vo.getProductionQuantity());
                    }
                }

                //查询合格数不合格数
                for (ProductionPlanProDetailVO vo : vos2) {
                    if (vo.getProductDetailId().equals(record.getProductDetailId())) {
                        record.setNoOkQuantity(vo.getNoOkQuantity());
                        record.setOkQuantity(vo.getOkQuantity());
                        record.setReportQuantity(vo.getReportQuantity());
                    }
                }

                for (ProductionPlanProDetailVO vo : vos3) {
                    if (vo.getProductDetailId().equals(record.getProductDetailId())) {
                        record.setInWarehouseQuantity(vo.getInWarehouseQuantity());
                    }
                }

                if (ObjectUtil.isEmpty(record.getInWarehouseQuantity()) || record.getInWarehouseQuantity().compareTo(BigDecimal.ZERO)<=0){
                    record.setCompletionRate(BigDecimal.ZERO);
                }else{
                    BigDecimal result =  record.getInWarehouseQuantity().divide(BigDecimal.valueOf(record.getProductionPlanQuantity()),2, RoundingMode.HALF_UP);
                    BigDecimal percentage = result.multiply(new BigDecimal(100));
                    record.setCompletionRate(percentage);
                }
            }
        }
        return new PageResult<>(planRecordCountInfo.getRecords(), planRecordCountInfo.getTotal());
    }


    /**
     * 根据物料查询在制品统计详情
     * @param productDetailId 物料id
     * @return
     */
    @ApiOperation(value = "在制品-详情",notes = "在制品-详情")
    @GetMapping("/detail/{productDetailId}")
    public JsonResult<ProductionPlanRecordReportDetailVO> detail(@PathVariable("productDetailId") Long productDetailId) {
        ProductionPlanRecordReportDetailVO byId = productionPlanRecordService.getProgressDetailBy(productDetailId);
        return JsonResult.success(byId);
    }

}
